<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Badger - handles authentication, authorization, and user management
 *
 * Utilizes OB_Session
 * +- XAcms -+
 * author: Chris Lunsford
 */
class Badger {

	var $CI;
	
	function __construct() {
		$this->CI =& get_instance();
		$this->CI->load->model('UserModel');
		$this->CI->load->model('RememberMe');
		$this->CI->load->helper('cookie');
	}
	
	/*
	 * Logs in the current user
	 * @param string username to be stored in session data
	 */
	function login($username) {
		$session = array('username' => $username, 'loggedin' => TRUE);
		log_message('info','User: '.$username.' logged in.');
		$this->CI->session->set_userdata($session);
	}
	
	/*
	 * Logs out the current user
	 */
	function logout() {
		$session = array('username' => '', 'loggedin' => FALSE);
		$this->CI->session->set_userdata($session);
		//should we just delete the session instead?
		//$this->CI->session->sess_destroy();
		//and delete our cookies, too?
		$this->removeRememberMe();
	}
	
	/*
	 * Returns whether or not the current user is logged in
	 *
	 * @return boolean TRUE if logged in / FALSE otherwise
	 */
	function isloggedin() {
		$username = $this->CI->session->userdata('username');
		$loggedin = $this->CI->session->userdata('loggedin');
		
		if ((isset($username) && $username != '') && (isset($loggedin) && $loggedin == TRUE)) {
			return TRUE;
		} else {
			return FALSE;
		}
	}
	
	/*
	 * Processes to see if the user should be logged in from remember me, that's all.
	 * 
	 * @return boolean TRUE if user is logged in
	 */
	function checkRemember() {
		//this should only do anything if they aren't already logged in
		if (!$this->isloggedin()) {
			//User is not logged in, check to see if they should be
			$hash = $this->CI->input->cookie('cl_user', TRUE);
			$string = $this->CI->input->cookie('cl_ranstring', TRUE);
			$check = $this->CI->RememberMe->checkRememberMe($hash, $string); //grab the username or FALSE
				
			if ($check != FALSE) {
				//login the user returned from the RememberMe Check
				$this->login($check);
				$this->CI->UserModel->updateLastActivity($this->CI->session->userdata('username'));
				return TRUE; //and they are now logged in
			} else {
				return FALSE;
			}
		}
	}
	
	/*
	 * Function to check whether or not a user is logged in or requires a remember me login to take place
	 * @return boolean TRUE if user is logged in, FALSE if not
	 */
	function checkState() {
		//determine if the user is logged in
		if ($this->isloggedin()) {
			$this->CI->UserModel->updateLastActivity($this->CI->session->userdata('username'));
			return TRUE;
		} else {
			if ($this->checkRemember()) {
				return TRUE;
			} else {
				//remember where we were trying to get, so we can take them back again after login
				$this->CI->session->set_userdata('redirect', $this->CI->uri->uri_string());
				redirect('site/login'); //not logged in, let's have them login
			}
		}
	}
	
	/**
	 * @param boolean TRUE = user must be logged in to view page, FALSE = just check to see if remember me needs to kick in
	 * @param string Space-separated list of allowed groups
	 * @return boolean this user is allowed / or not allowed to view this page
	 */
	function checkAllow($allowed_groups_list=null) {
		//Including this call allows us to make only one function call in a controller to check for both state and permission
		if ($this->checkState()) {
			//only logged in users are considered for permission checks
			if ($allowed_groups_list != null) {
				$userid = $this->CI->UserModel->getUserID($this->CI->session->userdata('username'));
			
				$group = explode(' ', $allowed_groups_list); //grab list of allowed groups, explode by space separation into array
				foreach ($group as $i) {
					if ($this->CI->UserModel->isUserInGroup($userid, $this->CI->UserModel->getGroupID($i))) {
						return TRUE; //if user in any of the allowed groups, exit procedure return TRUE
					}
				}
			}
		}
		//if all else fails, kick the user out
		redirect('site/deadend');	
	}
	
	/*****************************
	 * User Management functions *
	 *****************************/
	
	/**
	 *
	 *
	 */
	function register() {
		//grab the post information for adding user
		$post['username'] = $this->CI->input->post('username', TRUE);
		$post['lastname'] = $this->CI->input->post('lastname', TRUE);
		$post['firstname'] = $this->CI->input->post('firstname', TRUE);
		$post['password'] = $this->CI->input->post('password', TRUE);
		$post['email'] = $this->CI->input->post('email', TRUE);
		
		//add user to the database			
		$this->CI->UserModel->createUser($post);
	}
	
	function addRememberMe($username) {
		//clear old cookie
		$this->removeRememberMe();
		$this->CI->load->helper('string');
		$this->CI->load->helper('security');
		
		$random_string = random_string('alnum', 128);
		$info = array(
			'username' => $username,
			'usernamehash' => dohash($username),
			'random_string' => $random_string,
			'origin_time' => now()
		);
				
		$this->CI->RememberMe->addRememberMe($info);
		set_cookie("cl_user", dohash($username), $this->CI->config->item('remember_me_life'));
		set_cookie("cl_ranstring", $random_string, $this->CI->config->item('remember_me_life'));
	}

	function removeRememberMe() {
		$hash = $this->CI->input->cookie('cl_user', TRUE);
		$string = $this->CI->input->cookie('cl_ranstring', TRUE);
		$this->CI->RememberMe->removeRememberMe($hash, $string);
		
		set_cookie("cl_user");
		set_cookie("cl_ranstring");
		//or should we delete the cookies instead?
		//delete_cookie("xa_user");
		//delete_cookie("xa_ranstring");
	}
	
}
?>